<template>
  <view v-if="visible" class="modal-overlay" @click="closeModal">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">{{ isEdit ? '编辑课程' : '添加课程' }}</text>
        <uni-icons type="closeempty" size="24" @click="closeModal" />
      </view>

      <scroll-view scroll-y class="modal-body">
        <!-- 课程选择 -->
        <view class="form-group">
          <text class="label">课程名称</text>
          <picker
            :value="formData.subjectId"
            :range="subjectOptions"
            range-key="subjects"
            @change="onSubjectChange"
            class="picker"
          >
            <view class="picker-text">
              {{ selectedSubjectName || '请选择课程' }}
            </view>
          </picker>
        </view>

        <!-- 教师选择 -->
        <view class="form-group">
          <text class="label">教师</text>
          <picker
            :value="formData.teacherId"
            :range="teacherOptions"
            range-key="teacherName"
            @change="onTeacherChange"
            class="picker"
          >
            <view class="picker-text">
              {{ selectedTeacherName || '请选择教师' }}
            </view>
          </picker>
        </view>

        <!-- 教室选择 -->
        <view class="form-group">
          <text class="label">教室</text>
          <picker
            :value="formData.classRoomId"
            :range="classroomOptions"
            range-key="className"
            @change="onClassroomChange"
            class="picker"
          >
            <view class="picker-text">
              {{ selectedClassroomName || '请选择教室' }}
            </view>
          </picker>
        </view>

        <view class="form-group">
          <text class="label">日期</text>
          <picker mode="date" :value="formData.date" @change="onDateChange" class="picker">
            <view class="picker-text">
              {{ formData.date || '请选择日期' }}
            </view>
          </picker>
        </view>

        <view class="form-row">
          <view class="form-group half">
            <text class="label">开始时间</text>
            <picker
              mode="time"
              :value="formData.startTime"
              @change="onStartTimeChange"
              class="picker"
            >
              <view class="picker-text">
                {{ formData.startTime || '请选择' }}
              </view>
            </picker>
          </view>

          <view class="form-group half">
            <text class="label">结束时间</text>
            <picker mode="time" :value="formData.endTime" @change="onEndTimeChange" class="picker">
              <view class="picker-text">
                {{ formData.endTime || '请选择' }}
              </view>
            </picker>
          </view>
        </view>

        <!-- 智能建议展示 -->
        <view v-if="suggestions.length > 0" class="suggestions-section">
          <text class="section-title">智能推荐</text>
          <view
            v-for="(suggestion, index) in filteredSuggestions"
            :key="index"
            class="suggestion-item"
            @click="applySuggestion(suggestion as unknown as SmartScheduleSuggestion)"
          >
            <text class="suggestion-time">
              {{ weekdays[suggestion.dayOfWeek] }} {{ suggestion.startTime }}-{{
                suggestion.endTime
              }}
            </text>
            <text class="suggestion-reason">{{ suggestion.reason }}</text>
          </view>
        </view>

        <!-- 冲突检测 -->
        <view v-if="conflicts.length > 0" class="conflicts-section">
          <text class="section-title warning">时间冲突</text>
          <view v-for="(conflict, index) in conflicts" :key="index" class="conflict-item">
            <uni-icons type="info" size="16" color="#ff4d4f" />
            <text class="conflict-text">{{ conflict.message }}</text>
          </view>
        </view>
      </scroll-view>

      <view class="modal-footer">
        <button class="btn-cancel" @click="closeModal">取消</button>
        <button
          class="btn-confirm"
          @click="confirmAdd"
          :disabled="!isFormValid || conflicts.length > 0"
        >
          确认添加
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import type { ScheduleItem, SmartScheduleSuggestion, ScheduleConflict } from '@/types/schedule'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'
import { getTeacherListApi } from '@/services/teacher.ts'
import { getClassRoomListApi } from '@/services/classRoom'
import type { TeacherItem } from '@/types/teacher'
import type { ClassRoomItem } from '@/types/classRoom'
import type { SubjectItem, SubjectParams } from '@/types/subject.ts'
import { getSubjectListApi } from '@/services/subject'

const props = defineProps<{
  visible: boolean
  teacherId?: string
  suggestions: SmartScheduleSuggestion[]
}>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  add: [schedule: ScheduleItem]
}>()

const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

const formData = ref({
  subjectId: '',
  subjectName: '',
  teacherId: '',
  teacherName: '',
  classRoomId: '',
  classRoomName: '',
  date: '',
  startTime: '',
  endTime: '',
})

const isEdit = ref(false)
const conflicts = ref<ScheduleConflict[]>([])

// 所有数据
const teacherOptions = ref<TeacherItem[]>([])
const classroomOptions = ref<ClassRoomItem[]>([])
const subjectOptions = ref<SubjectItem[]>([])

// 获取所有数据
const getTeacherList = async () => {
  const res = await getTeacherListApi({
    pageNum: 1,
    pageSize: 100,
  })
  teacherOptions.value = res.data.rows
}

const getClassRoomList = async () => {
  const res = await getClassRoomListApi({
    pageNum: 1,
    pageSize: 100,
  })
  classroomOptions.value = res.data.rows
}

const getSubjectList = async () => {
  const res = await getSubjectListApi({
    pageNum: 1,
    pageSize: 100,
  })
  subjectOptions.value = res.data.rows
}

onMounted(() => {
  getTeacherList()
  getClassRoomList()
  getSubjectList()
})

// 计算属性：选择的课程名称
const selectedSubjectName = computed(() => {
  const subject = subjectOptions.value.find((s) => s.id?.toString() === formData.value.subjectId)
  return subject?.subjects
})

// 计算属性：选择的教师名称（直接使用所有教师选项）
const selectedTeacherName = computed(() => {
  const teacher = teacherOptions.value.find((t) => t.id?.toString() === formData.value.teacherId)
  return teacher?.teacherName
})

// 计算属性：选择的教室名称（直接使用所有教室选项）
const selectedClassroomName = computed(() => {
  const classroom = classroomOptions.value.find(
    (c) => c.id?.toString() === formData.value.classRoomId,
  )
  return classroom?.className
})

const filteredSuggestions = computed(() => {
  if (!formData.value.teacherId) return []

  const suggestion = props.suggestions.find((s) => s.teacherId === formData.value.teacherId)
  return suggestion?.recommendations || []
})

const isFormValid = computed(() => {
  return (
    formData.value.subjectId &&
    formData.value.teacherId &&
    formData.value.classRoomId &&
    formData.value.date &&
    formData.value.startTime &&
    formData.value.endTime
  )
})

// 监听课程变化，重置教师和教室选择
watch(
  () => formData.value.subjectId,
  (newSubjectId) => {
    if (newSubjectId) {
      // 重置教师和教室选择
      formData.value.teacherId = ''
      formData.value.teacherName = ''
      formData.value.classRoomId = ''
      formData.value.classRoomName = ''

      // 如果只有一个教师，自动选择
      if (teacherOptions.value.length === 1) {
        const teacher = teacherOptions.value[0]
        formData.value.teacherId = teacher.id?.toString() || ''
        formData.value.teacherName = teacher.teacherName
      }

      // 如果只有一个教室，自动选择
      if (classroomOptions.value.length === 1) {
        const classroom = classroomOptions.value[0]
        formData.value.classRoomId = classroom.id?.toString() || ''
        formData.value.classRoomName = classroom.className || ''
      }
    }
  },
)

// 监听时间变化，检测冲突
watch(
  [() => formData.value.date, () => formData.value.startTime, () => formData.value.endTime],
  () => {
    checkConflicts()
  },
)

const checkConflicts = () => {
  if (!formData.value.date || !formData.value.startTime || !formData.value.endTime) {
    conflicts.value = []
    return
  }

  conflicts.value = []
  const selectedDate = new Date(formData.value.date)
  const dayOfWeek = selectedDate.getDay()

  if (formData.value.startTime === '09:00') {
    conflicts.value.push({
      time: `${formData.value.date} 09:00`,
      type: 'teacher',
      message: '该时间段已有课程安排',
    })
  }
}

const onSubjectChange = (e: any) => {
  const index = e.detail.value
  const subject = subjectOptions.value[index]
  formData.value.subjectId = subject.id?.toString() || ''
  formData.value.subjectName = subject.subjects || ''
}

const onTeacherChange = (e: any) => {
  const index = e.detail.value
  const teacher = teacherOptions.value[index]
  formData.value.teacherId = teacher.id?.toString() || ''
  formData.value.teacherName = teacher.teacherName
}

const onClassroomChange = (e: any) => {
  const index = e.detail.value
  const classroom = classroomOptions.value[index]
  formData.value.classRoomId = classroom.id?.toString() || ''
  formData.value.classRoomName = classroom.className || ''
}

const onDateChange = (e: any) => {
  formData.value.date = e.detail.value
}

const onStartTimeChange = (e: any) => {
  formData.value.startTime = e.detail.value
}

const onEndTimeChange = (e: any) => {
  formData.value.endTime = e.detail.value
}

const applySuggestion = (suggestion: SmartScheduleSuggestion) => {
  const now = new Date()
  const monday = new Date(now)
  monday.setDate(now.getDate() - (now.getDay() || 7) + 1 + (suggestion.dayOfWeek || 0))

  formData.value.date = monday.toISOString().split('T')[0]
  formData.value.startTime = suggestion.startTime || ''
  formData.value.endTime = suggestion.endTime || ''
}

const confirmAdd = () => {
  const schedule: ScheduleItem = {
    subjectId: formData.value.subjectId || '',
    subjectName: formData.value.subjectName || '',
    teacherName: formData.value.teacherName || '',
    teacherId: formData.value.teacherId || '',
    classRoomName: formData.value.classRoomName || '',
    classRoomId: parseInt(formData.value.classRoomId || '0'),
    startDatetime: `${formData.value.date} ${formData.value.startTime}`,
    endDatetime: `${formData.value.date} ${formData.value.endTime}`,
    studentNum: 0,
  }

  emit('add', schedule)
  closeModal()
}

const closeModal = () => {
  emit('update:visible', false)
  resetForm()
}

const resetForm = () => {
  formData.value = {
    subjectId: '',
    subjectName: '',
    teacherId: props.teacherId || '',
    teacherName: '',
    classRoomId: '',
    classRoomName: '',
    date: '',
    startTime: '',
    endTime: '',
  }
  conflicts.value = []
}

if (props.teacherId) {
  formData.value.teacherId = props.teacherId
  const teacher = teacherOptions.value.find((t) => t.id === props.teacherId)
  if (teacher) {
    formData.value.teacherName = teacher.teacherName
  }
}
</script>

<style scoped lang="scss">
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4rpx);
}

.modal-content {
  background-color: white;
  border-radius: 24rpx;
  width: 90%;
  max-width: 640rpx;
  max-height: 85vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 36rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fafafa;
}

.modal-title {
  font-size: 34rpx;
  font-weight: 700;
  color: $text-main;
}

.modal-body {
  flex: 1;
  padding: 32rpx 36rpx;
}

.form-group {
  margin-bottom: 36rpx;
}

.form-row {
  display: flex;
  gap: 24rpx;
}

.half {
  flex: 1;
}

.label {
  display: block;
  font-size: 30rpx;
  color: $text-main;
  margin-bottom: 16rpx;
  font-weight: 600;
  line-height: 1.4;
}

.input {
  width: 100%;
  padding: 24rpx 28rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 16rpx;
  font-size: 32rpx;
  color: $text-main;
  background-color: #fafafa;
  transition: all 0.3s ease;
  line-height: 1.5;
  box-sizing: border-box;
  min-height: 88rpx;
}

.input:focus-within {
  border-color: $primary-color;
  background-color: #ffffff;
  box-shadow: 0 0 0 4rpx rgba(41, 121, 255, 0.1);
}

.input::placeholder {
  color: #999999;
  font-size: 30rpx;
  font-weight: 400;
}

.input:hover {
  border-color: #cccccc;
}

.picker {
  width: 100%;
}

.picker-text {
  padding: 24rpx 28rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 16rpx;
  font-size: 32rpx;
  color: $text-main;
  background-color: #fafafa;
  min-height: 88rpx;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.picker-text:hover {
  border-color: #cccccc;
}

.picker-text.disabled {
  background-color: #f5f5f5;
  color: #999999;
  cursor: not-allowed;
}

.suggestions-section,
.conflicts-section {
  margin-top: 32rpx;
  padding: 24rpx;
  border-radius: 16rpx;
}

.suggestions-section {
  background-color: rgba(41, 121, 255, 0.08);
}

.conflicts-section {
  background-color: rgba(255, 77, 79, 0.08);
}

.section-title {
  font-size: 30rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
  color: $text-main;

  &.warning {
    color: #ff4d4f;
  }
}

.suggestion-item {
  padding: 20rpx;
  background-color: white;
  border-radius: 12rpx;
  margin-bottom: 12rpx;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1rpx solid #f0f0f0;
}

.suggestion-item:hover {
  background-color: #f8f8f8;
  border-color: #e0e0e0;
}

.suggestion-time {
  display: block;
  font-size: 30rpx;
  font-weight: 600;
  color: $primary-color;
  margin-bottom: 8rpx;
}

.suggestion-reason {
  display: block;
  font-size: 26rpx;
  color: #666666;
}

.conflict-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 12rpx 0;
}

.conflict-text {
  font-size: 28rpx;
  color: #ff4d4f;
  line-height: 1.4;
}

.modal-footer {
  display: flex;
  gap: 24rpx;
  padding: 32rpx 36rpx;
  border-top: 1rpx solid #f0f0f0;
  background-color: #fafafa;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  padding: 24rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  transition: all 0.2s ease;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: $text-main;
  border: 1rpx solid #e0e0e0;
}

.btn-cancel:hover {
  background-color: #eeeeee;
}

.btn-confirm {
  background-color: $primary-color;
  color: white;
  border: 1rpx solid $primary-color;
}

.btn-confirm:hover {
  background-color: #1a5eff;
}

.btn-confirm:disabled {
  background-color: #d9d9d9;
  color: #bfbfbf;
  border-color: #d9d9d9;
  cursor: not-allowed;
}

/* 响应式调整 */
@media screen and (max-width: 375px) {
  .modal-content {
    width: 95%;
    border-radius: 20rpx;
  }

  .input,
  .picker-text {
    font-size: 30rpx;
    padding: 22rpx 24rpx;
  }

  .label {
    font-size: 28rpx;
  }
}

/* 暗色模式支持 */
@media (prefers-color-scheme: dark) {
  .modal-content {
    background-color: #1a1a1a;
  }

  .modal-header,
  .modal-footer {
    background-color: #252525;
  }

  .input,
  .picker-text {
    background-color: #2a2a2a;
    border-color: #404040;
    color: #ffffff;
  }

  .input:focus-within {
    background-color: #333333;
  }

  .input::placeholder {
    color: #666666;
  }

  .picker-text.disabled {
    background-color: #333333;
    color: #666666;
  }
}
</style>
